package org.csu.demo.persistence;

import org.csu.demo.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Repository
public class AccountDAOImpl implements AccountDAO{

    @Autowired
    private DataSource dataSource;

    @Override
    public Account findByUsernameAndPassword(Account account) {
        Account loginAccount = null;
        try{
            //*************连接数据库的语句**************
            Connection connection = dataSource.getConnection();
            //System.out.println("TEST......."+connection);
            PreparedStatement pStatement = connection.prepareStatement(FIND_BY_USERNAME_AND_PASSWORD);

            pStatement.setString(1,account.getUsername());
            pStatement.setString(2,account.getPassword());

            ResultSet resultSet = pStatement.executeQuery();
            if(resultSet.next()){
                loginAccount = new Account();
                loginAccount.setId(resultSet.getInt("uid"));
                loginAccount.setUsername(resultSet.getString("username"));
                loginAccount.setPassword(resultSet.getString("password"));
            }

            resultSet.close();
            pStatement.close();
            connection.close();


        }catch (Exception e){
            e.printStackTrace();
        }
        return loginAccount;
    }
}
